import React from 'react';
import { Tree, Spin, Empty, Typography } from 'antd';
import cn from 'classnames';
import styles from './style.less';

const RankTree = ({ treeData = [], onSelect, title, loading, defaultSelectedKeys }) => {
    const renderTitle = (data = {}) => {
        const { title: _title, state } = data;
        const isDelete = state === 3;
        const finalTitle = isDelete ? `${_title} (已删除)` : _title;

        return (
            <Typography.Paragraph ellipsis style={{ width: 180, marginBottom: 0, color: 'inherit' }} title={finalTitle}>
                <span className={cn({ disabled: isDelete })}>{finalTitle}</span>
            </Typography.Paragraph>
        );
    };

    const putDeletedDataToLast = list => {
        const arr1 = [];
        const arr2 = [];
        if (!list || list.length === 0) {
            return list;
        }
        list.forEach(element => {
            if (element.state === 3) {
                arr2.push(element);
            } else {
                arr1.push(element);
            }
        });
        return [...arr1, ...arr2];
    };

    const renderTreeNode = data => {
        const sortedData = putDeletedDataToLast(data);
        return sortedData.map(item => {
            if (item.children && item.children.length) {
                const sortedChildren = putDeletedDataToLast(item.children);
                return (
                    <Tree.TreeNode key={item.key} title={renderTitle(item)}>
                        {renderTreeNode(sortedChildren)}
                    </Tree.TreeNode>
                );
            }
            return <Tree.TreeNode key={item.key} title={renderTitle(item)} />;
        });
    };

    const renderTree = () => {
        if (loading) {
            return <Spin spinning={loading} />;
        }

        if (treeData.length === 0) {
            return <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />;
        }

        const sortedTreeData = putDeletedDataToLast(treeData);

        return (
            <Tree defaultExpandAll onSelect={onSelect} defaultSelectedKeys={defaultSelectedKeys}>
                {sortedTreeData.map(item => (
                    <Tree.TreeNode key={item.key} title={renderTitle(item)}>
                        {renderTreeNode(item.children)}
                    </Tree.TreeNode>
                ))}
            </Tree>
        );
    };

    return (
        <div className={styles.wrap}>
            <div className={styles.title}>{title}</div>
            <div className={styles.tree}>{renderTree()}</div>
        </div>
    );
};

export default RankTree;
